package com.bootcamp.javase2.stream;

import java.io.*;
import java.util.Arrays;
import java.util.Random;

/**
 * @program: CharacterStreamCode
 * @description:
 * @author: Keyu Li
 * @create: 2021-09-10 20:04
 **/

public class SortLetter {
    final static String FILE_NAME = "letters.txt";

    public static void main(String[] args) throws IOException {
        //create random letters file
        createRandomLetters(FILE_NAME);

        // read file
        // create buffered reader object
        BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME));
        char[] letters = reader.readLine().toCharArray();

        // sort char array
        // call java fileutils
//        Arrays.sort(letters);
        // my sort
        InsertionSort(letters);

        // write file
        // create buffered writer object
        BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_NAME, true));
        writer.newLine();
        writer.write(letters);

        // close
        reader.close();
        writer.close();
    }

    private static void InsertionSort(char[] array) {
        for (int i = 1; i < array.length; i++) {
            int j;
            char temp = array[i];
            for (j = i - 1; j >= 0; j--) {
                if (temp < array[j]) {
                    array[j + 1] = array[j];
                } else
                    break;
            }
            array[j + 1] = temp;
        }
    }

    private static void createRandomLetters(String s) throws IOException {
        int[] flag = new int[26];
        char[] letters = new char[26];
        Random rd = new Random();
        for (int i = 0; i < 26; i++) {
            int rdLetter = rd.nextInt(10000) % 26;
            if (flag[rdLetter] == 1) {
                i--;
                continue;
            } else {
                flag[rdLetter] = 1;
                letters[i] = (char) (rdLetter + 97);
            }
        }
//        System.out.println(new String(letters));
        // create file and write
        BufferedWriter writer = new BufferedWriter(new FileWriter(s));
        writer.write(letters);
        writer.close();
    }
}
